<?php
// +----------------------------------------------------------------------
// | 知识星球[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 abcblockchain.io
// +----------------------------------------------------------------------
// | 后台管理使用了HisiPHP
// +----------------------------------------------------------------------
// | Author: abcblockchain.io
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;
use think\Db;

/**
 * 消息模型
 * @package app\common\model
 */
class Message extends Model
{
    // 定义时间戳字段名
    protected $createTime = 'ctime';
    protected $updateTime = false;

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;


    /**
     * 创建消息
     * @author
     * @param $userId
     * @param $msg_type
     * @param int $from_uid
     * @param int $group_id
     * @param int $post_id
     * @return bool|int|string
     */
    public function createMsg($userId,$msgType,$fromUid=0,$fromNick='',$groupId=0,$postId=0)
    {
        $map = [];
        $map['user_id'] = $userId;
        $map['msg_type'] = $msgType;
        $map['from_uid'] = $fromUid;
        $map['from_nick'] = $fromNick;
        $map['group_id'] = $groupId;
        $map['post_id'] = $postId;
        $map['is_read'] = 0;
        $map['status'] = 1;
        $map['ctime'] = time();
        $res = $this->insertGetId($map);
        if($res){
            return $res;
        }else{
            return false;
        }
    }

    /**
     * 更新消息阅读状态
     * @author
     * @param $msgId
     * @return bool
     */
    public function updateRead($msgId)
    {
        $map['id'] = $msgId;
        $save['is_read'] = 1;
        $res = $this->where($map)->update($save);
        if($res === false){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 获取消息列表
     * @author
     * @param $userId
     * @param int $type
     * @param int $startNo
     * @param int $limit
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getMsg($userId,$type=1, $startNo = 0, $limit = 15){
        $map = [];
        $map['m.user_id'] = $userId;
        $map['m.msg_type'] = $type;
       /* if($type){
            $map['from_uid'] = array('gt',0);
        }else{
            $map['from_uid'] = 0;
        }*/
        $startNo = $startNo * $limit;
        $map['m.status'] = 1;
        $msgList = $this->alias('m')->join('users u','m.from_uid=u.id','LEFT')->join('group g','m.group_id=g.id','LEFT')->join('group_posts p','m.post_id=p.id','LEFT')->where($map)->order('m.ctime desc')->field('m.*,p.body,g.name as group_name,u.avatar')->limit($startNo, $limit)->select();
        return $msgList ? $msgList : array();
    }

}